package cn.yeziji.forum.dao.impl;

import cn.yeziji.forum.bo.special.DetailSpecialDTO;
import cn.yeziji.forum.common.enums.ForumCommonStatus;
import cn.yeziji.forum.converter.SpecialConverter;
import cn.yeziji.forum.dao.base.ForumSpecialColumnBaseDao;
import cn.yeziji.forum.dao.intf.ForumSpecialColumnDao;
import cn.yeziji.forum.dao.intf.ForumUserDao;
import cn.yeziji.forum.dao.iquery.SpecialQuery;
import cn.yeziji.forum.entity.ForumSpecialColumnEntity;
import cn.yeziji.forum.entity.ForumUserEntity;
import cn.yeziji.forum.exception.ForumException;
import cn.yeziji.forum.utils.JwtOperaUtils;
import cn.yeziji.forum.vo.special.SpecialVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 专栏服务实现层
 *
 * @author gzkemays
 * @since 2022/5/25 12:12:23
 */
@Repository
public class ForumSpecialColumnDaoImpl extends ForumSpecialColumnBaseDao
    implements ForumSpecialColumnDao {
  @Resource HttpServletRequest request;
  @Resource ForumUserDao userDao;

  @Override
  public int save(DetailSpecialDTO dto) {
    String username = JwtOperaUtils.getUserNameByRequest(request);
    dto.setUsername(username);
    ForumSpecialColumnEntity one =
        mapper.findOne(SpecialQuery.getSpecialByNameAndUsername(dto.getName(), username));
    if (one == null) {
      ForumSpecialColumnEntity entity = dto.buildEntity();
      mapper.insert(entity);
      return entity.getId();
    }
    return one.getId();
  }

  @Override
  public List<SpecialVO> getSpecialsByUser() {
    return SpecialConverter.INSTANCE.entitiesConvertToVos(
        mapper.listEntity(
            SpecialQuery.getSpecialsByUsername(JwtOperaUtils.getUserNameByRequest(request))));
  }

  @Override
  public List<SpecialVO> getSpecialsByNickname(String nickname) {
    if (StringUtils.isBlank(nickname)) throw new ForumException(ForumCommonStatus.DATA_ERROR);
    ForumUserEntity userEntity = userDao.selectUserByNickName(nickname);
    return SpecialConverter.INSTANCE.entitiesConvertToVos(
        mapper.listEntity(SpecialQuery.getSpecialsByUsername(userEntity.getUsername())));
  }
}
